﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Hotel.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CommonController : ControllerBase
    {
        [HttpPost]   
        public  IActionResult PostUploadImage(IFormFile file)
        {
            try
            {
                //1.上传图片的大小
                var maxLength = 1024 * 1024 * 2;//2M
                if(file.Length > maxLength)
                {
                    return BadRequest (new {
                        msg ="上传的图片不能大天2M"
                    });
                }

                //2.图片上传的格式
                //列举所有的图片格式
                var imageMimeTypes = new List<string>
                   {
                        "image/jpg",
                        "image/jpeg",
                       "image/png",
                       "image/gif" ,
                       "image/webp"  
                       // 可以根据需要添加其他图片MIME类型
                       //,"image/bmp"
                       //,"image/tiff"
                       //,"image/webp"  
                   };

                //获取文件的MIME类型
                var mimeType = file.ContentType;

                // 检查文件的MIME类型是否在图片MIME类型列表中  
                if (!imageMimeTypes.Contains(mimeType))
                {
                    return BadRequest(new {msg = "上传的文件不是图片" });
                }

                //3.图片上传
                //拼接上传图片的路径
                var str = Guid.NewGuid();
                var savePath = Path.Combine("uploads", str +  file.FileName);

                
                using (var stream = new FileStream(savePath, FileMode.Create))
                {
                    //将上传的图片放到文件流中
                    //file.CopyToAsync(stream);
                    file.CopyTo(stream);

                }
                return Ok(new { fileName = "/uploads/" + str + file.FileName, size = file.Length });


            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
